﻿using B.S.NewMedical.Api.Write.Application.Command.Order.Prescription;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Order.Prescription
{
    /// <summary>
    /// 删除处方处理器
    /// </summary>
    public class DeletePrescriptionCommandHandle : IRequestHandler<DeletePrescriptionCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PrescriptionModel> _prescriptionRepository;
        private readonly ILogger<DeletePrescriptionCommandHandle> _logger;

        public DeletePrescriptionCommandHandle(
            IBaseRepository<PrescriptionModel> prescriptionRepository,
            ILogger<DeletePrescriptionCommandHandle> logger)
        {
            _prescriptionRepository = prescriptionRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DeletePrescriptionCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                _logger.LogInformation("开始删除处方记录，ID：{Id}", request.Id);

                // 1. 查找要删除的处方记录
                var prescription = _prescriptionRepository.GetAll()
                    .FirstOrDefault(x => x.Id == request.Id && !x.IsDeleted);

                if (prescription == null)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "未找到要删除的处方记录";
                    _logger.LogWarning("未找到要删除的处方记录，ID：{Id}", request.Id);
                    return result;
                }

                // 2. 检查处方记录状态，防止删除已完成的订单
                if (!string.IsNullOrEmpty(prescription.Orderstatus) && 
                    prescription.Orderstatus.Equals("已完成", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已完成的处方订单不能删除";
                    _logger.LogWarning("尝试删除已完成的处方订单，ID：{Id}，状态：{Status}", 
                        request.Id, prescription.Orderstatus);
                    return result;
                }

                // 3. 检查处方单状态，防止删除已审核的处方
                if (!string.IsNullOrEmpty(prescription.PrescriptionStatus) && 
                    prescription.PrescriptionStatus.Equals("已审核", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已审核的处方不能删除";
                    _logger.LogWarning("尝试删除已审核的处方，ID：{Id}，处方状态：{Status}", 
                        request.Id, prescription.PrescriptionStatus);
                    return result;
                }

                // 4. 检查发药状态，防止删除已发药的处方
                if (!string.IsNullOrEmpty(prescription.MedicationStatus) && 
                    prescription.MedicationStatus.Equals("已发药", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已发药的处方不能删除";
                    _logger.LogWarning("尝试删除已发药的处方，ID：{Id}，发药状态：{Status}", 
                        request.Id, prescription.MedicationStatus);
                    return result;
                }

                // 5. 执行逻辑删除
                prescription.IsDeleted = true;
                prescription.UpdateTime = DateTime.Now;

                // 6. 更新数据库
                var updateResult = await _prescriptionRepository.UpdateAsync(prescription);

                if (updateResult > 0)
                {
                    result.Code = ApiEnum.Success;
                    result.Msg = "处方记录删除成功";
                    result.Data = updateResult;
                    
                    _logger.LogInformation("处方记录删除成功，ID：{Id}，处方编号：{PrescriptionId}，患者：{Patient}，医生：{Doctor}，费用：{Cost}", 
                        prescription.Id, prescription.PrescriptionId, prescription.Patient, prescription.Doctor, prescription.Cost);
                }
                else
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "处方记录删除失败";
                    result.Data = updateResult;
                    
                    _logger.LogError("处方记录删除失败，ID：{Id}", request.Id);
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"删除处方记录时发生异常：{ex.Message}";
                
                _logger.LogError(ex, "删除处方记录时发生异常，ID：{Id}，异常信息：{Message}", 
                    request.Id, ex.Message);
            }

            return result;
        }
    }
}
